# -*- coding: utf-8 -*-
"""
Created on Tue Nov 14 10:32:33 2017

@author: za-xuzhaoye
"""
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from statsmodels.tsa.stattools import adfuller,coint
import statsmodels.api as sm

#协整性检验
def testStationarity(data):
    adftest = adfuller(data)
    result = pd.Series(adftest[0:4], index=['Test Statistic','p-value','Lags Used','Number of Observations Used'])
    for key,value in adftest[4].items():
        result['Critical Value (%s)'%key] = value
    return result

data=pd.read_csv('D:\FOF_strategy\A&H_ETF_data\ClosePrice.csv')
data.date=data.date.astype(str)
data.date=pd.to_datetime(data.date)

hzetf1=data['HZETF']
hzetf=np.array(hzetf1)
hstetf1=data['513660HSTETF']
hstetf=np.array(hstetf1)

zz=pd.concat([testStationarity(hzetf),testStationarity(hstetf)],axis=1)
zz.columns=['hzetf','hstetf']

diff_hzetf = hzetf1.diff(1)
diff_hzetf.dropna(inplace=True)
diff_hzetf=np.array(diff_hzetf)

diff_hstetf = hstetf1.diff(1)
diff_hstetf.dropna(inplace=True)
diff_hstetf=np.array(diff_hstetf)
tz=pd.concat([testStationarity(diff_hzetf),testStationarity(diff_hstetf)],axis=1)
tz.columns=['hetf','szetf']

coint_test= coint(hzetf,hstetf)[1]

#OLS
x=hzetf
y=hstetf
X=sm.add_constant(x)
result=(sm.OLS(y,X)).fit()
print(result.summary())

#基于513600恒指etf 和 513660恒生通的套利策略
#mean=(hstetf1-1.0316*hzetf1).mean()
#std=(hstetf1-1.0316*hzetf1).std()
mean=(hstetf1-hzetf1).mean()
std=(hstetf1-hzetf1).std()
up=mean+std
down=mean-std
s1=pd.Series(mean,index=range(len(hzetf)))
up_line=pd.Series(up,index=range(len(hzetf)))
down_line=pd.Series(down,index=range(len(hzetf)))
data3=pd.concat([hstetf1-hzetf1,s1,up_line,down_line],axis=1)
data3.columns=['spreadprice','mean','upper','down']
print "UP is "+str(up),"down is "+str(down),"STD is "+str(std)

data3.plot(figsize=(15,7))

